package com.web.exiaodao.business.controller;
import com.web.exiaodao.business.service.InstitutionService;
import com.web.exiaodao.remote.vo.InstitutionVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.controller.BaseController;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.WebUitl;
import com.web.webstart.base.util.result.XaResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: InstitutionController.java
 * @Package com.web.webstart.business.controller
 * @Description: 机构表控制器
 * @author eason.zt
 * @date 2016-11-04 10:01:30
 * @version V1.0
 */
@Controller
@RequestMapping("/cms/institution")
public class InstitutionController extends BaseController {

	private static final Logger LOGGER = Logger.getLogger(InstitutionController.class);

	@Autowired
	private InstitutionService institutionService;
	
	/**
	 * @Title: findInstitutionNEStatusPage
	 * @Description: 分页查询Institution	 * @param nextPage
	 * @param pageSize
	 * @param status		//默认查询非删除3的数据,具体类型参照XaConstant.Status
	 * @param sortData
	 * @param jsonFilter
	 * @return    
	 */
	@ResponseBody
	@RequestMapping(value="findInstitutionNEStatusPage",method=RequestMethod.POST)
	public XaResult<Page<InstitutionVo>> findInstitutionNEStatusPage(
		@RequestParam(defaultValue = "0") Integer nextPage,
		@RequestParam(defaultValue = "10") Integer pageSize,
		@RequestParam(defaultValue = "3") Integer status,
		@RequestParam(defaultValue = "[{property:'sort',direction:'ASC'},{property:'clickCont',direction:'DESC'},{property:'createTime',direction:'DESC'}]") String sortData,
		@RequestParam(defaultValue = "{}") String jsonFilter
	) throws BusinessException{
		XaResult<Page<InstitutionVo>> xr = new XaResult<Page<InstitutionVo>>();
		Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, sortData);
		Map<String,Object> filterParams =  WebUitl.getParametersStartingWith(jsonFilter, "search_");
		return institutionService.findListNEStatusByFilter(status, filterParams, pageable);
	}
	
	/**
	 * @Title: findInstitutionEQStatusPage
	 * @Description: (预留)分页查询Institution	 * @param nextPage
	 * @param pageSize
	 * @param status		//默认查询正常状态1的数据,具体类型参照XaConstant.Status
	 * @param sortData
	 * @param jsonFilter
	 * @return    
	 */
	@ResponseBody
	@RequestMapping(value="findInstitutionEQStatusPage",method=RequestMethod.POST)
	public XaResult<Page<InstitutionVo>> findInstitutionEQStatusPage(
		@RequestParam(defaultValue = "0") Integer nextPage,
		@RequestParam(defaultValue = "10") Integer pageSize,
		@RequestParam(defaultValue = "1") Integer status,
		@RequestParam(defaultValue = "[{property:'createTime',direction:'DESC'}]") String sortData,
		@RequestParam(defaultValue = "{}") String jsonFilter
	) throws BusinessException{
		XaResult<Page<InstitutionVo>> xr = new XaResult<Page<InstitutionVo>>();
		Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, sortData);
		Map<String,Object> filterParams =  WebUitl.getParametersStartingWith(jsonFilter, "search_");
		return institutionService.findListEQStatusByFilter(status, filterParams, pageable);
	}
	
	/**
	 * @Title: findInstitutionById
	 * @Description: 根据ID查找单条实体
	 * @param modelId
	 * @return    
	 */
	@ResponseBody
	@RequestMapping(value="findInstitutionById",method=RequestMethod.POST)
	public XaResult<InstitutionVo> findInstitutionById(
		@RequestParam Long modelId
	) throws BusinessException{
		XaResult<InstitutionVo> xr = new XaResult<InstitutionVo>();
		try{
			return institutionService.findOne(modelId);
		}catch(Exception e){
			LOGGER.error(XaConstant.Message.error,new Throwable(e));
			xr.error(XaConstant.Message.error);
		}
		return xr;
	}
	/**
	 * @Title: saveModel
	 * @Description: 保存实体数据
	 * @param model
	 * @return    
	 */
	@ResponseBody
	@RequestMapping(value="saveInstitution",method=RequestMethod.POST)
	public XaResult<InstitutionVo> saveInstitution(
		InstitutionVo model
	) throws BusinessException{
		XaResult<InstitutionVo> xr = new XaResult<InstitutionVo>();
		return institutionService.saveOrUpdate(model);
	}
	
	/**
	 * @Title: multiOperateInstitutionByIds
	 * @Description: 批量操作多个实体状态,根据status进行操作
	 * @param modelIds    	多个实体id,中间用逗号隔开
	 * @param status 		操作类型,status类型见XaConstant.Status,默认删除操作
	 * @return    
	 */
	@ResponseBody
	@RequestMapping(value="operateInstitutionByIds",method=RequestMethod.POST)
	public XaResult<InstitutionVo> operateInstitutionByIds(
		HttpServletRequest request,
		@RequestParam String modelIds,
		@RequestParam(defaultValue = "3") Integer status
	) throws BusinessException{
		XaResult<InstitutionVo> xr = new XaResult<InstitutionVo>();
		return institutionService.multiOperate(modelIds,status);
	}
	
	/**
     * @param photoFile
     * @param request
     * @return
     * @Title: upload
     * @Description: 图片上传
     */
    @ResponseBody
    @RequestMapping(value = "photoUpload", method = RequestMethod.POST)
    public XaResult<String> photoUpload(
            @RequestParam(value = "photoFile", required = false) MultipartFile photoFile,
            HttpServletRequest request) {
        XaResult<String> xr = new XaResult<String>();
        if (photoFile == null) {
            xr.error("请先选择上传的文件！");
            return xr;
        }
        if (photoFile.getSize() > XaConstant.FileMgr.IMG_MaxValue) {
            xr.error(XaConstant.FileMgr.IMG_ERROR);
            return xr;
        }
        String root = request.getSession().getServletContext().getRealPath("/");
        String picturePath = "/upload/institution";
        String ext = photoFile.getOriginalFilename().substring(
                photoFile.getOriginalFilename().lastIndexOf("."));
        String newName = new Date().getTime() + ext;
        File filedict = new File(root + picturePath);
        if (!filedict.exists()) {
            filedict.mkdir();
        }
        File targetFile = new File(root + picturePath + File.separator
                + newName);
        try {
            if (org.apache.commons.lang3.StringUtils.equalsIgnoreCase(ext, ".jpg")
                    || org.apache.commons.lang3.StringUtils.equalsIgnoreCase(ext, ".png")) {
                photoFile.transferTo(targetFile);
                BufferedImage bimg = ImageIO.read(targetFile);
                int width = bimg.getWidth();
                int height = bimg.getHeight();
                //Map<String, Integer> map = new HashMap<String, Integer>();
				//map.put("pictureHeight", height);
				//map.put("pictureWidth", width);
                xr.setCode(1);
                xr.setObject(XaConstant.Code.success + ":" + picturePath + "/"
                        + newName + ":" + height + ":" + width);
            } else {
                xr.setCode(0);
                xr.setObject(XaConstant.Code.error + ":上传文件类型不允许,请上传jpg/png图片");
            }
        } catch (IllegalStateException e) {
            xr.setCode(0);
            xr.setObject(XaConstant.Code.error + ":图片上传失败(Il)");
        } catch (IOException e) {
            xr.setCode(0);
            xr.setObject(XaConstant.Code.error + ":图片上传失败(IO)");
        } catch (Exception e) {
            xr.setCode(0);
            xr.setObject(XaConstant.Code.error + ":图片上传失败(Ex)");
        }
		return xr;
    }

	/**
	 * @param videoFile
	 * @param request
	 * @return
	 * @Title: upload
	 * @Description: 视频上传
	 */
    @ResponseBody
    @RequestMapping(value = "videoUpload", method = RequestMethod.POST)
    public XaResult<String> videoUpload(
				@RequestParam(value = "videoFile", required = false) MultipartFile videoFile,
            HttpServletRequest request) {
		XaResult<String> xr = new XaResult<String>();
        if (videoFile == null) {
            xr.error("请先选择上传文件！");
            return xr;
        }
        if (videoFile.getSize() > XaConstant.FileMgr.VIDEO_MaxValue) {
            xr.error(XaConstant.FileMgr.VIDEO_ERROR);
            return xr;
        }
		try {
            String root = request.getSession().getServletContext().getRealPath("/");
            String picturePath = "/upload/video";
            String ext = videoFile.getOriginalFilename().substring(
                    videoFile.getOriginalFilename().lastIndexOf("."));

            String newName = new Date().getTime() + ext;
            File filedict = new File(root + picturePath);
            if (!filedict.exists()) {
                filedict.mkdir();
            }
            File targetFile = new File(root + picturePath + File.separator
                    + newName);

			if (org.apache.commons.lang3.StringUtils.equalsIgnoreCase(ext, ".mp4")
					|| org.apache.commons.lang3.StringUtils.equalsIgnoreCase(ext, ".avi")
					|| org.apache.commons.lang3.StringUtils.equalsIgnoreCase(ext, ".rmvb")
					|| org.apache.commons.lang3.StringUtils.equalsIgnoreCase(ext, ".mov")
					|| org.apache.commons.lang3.StringUtils.equalsIgnoreCase(ext, ".wmv")
					|| org.apache.commons.lang3.StringUtils.equalsIgnoreCase(ext, ".3gp")
					) {
				videoFile.transferTo(targetFile);
				BufferedImage bimg = ImageIO.read(targetFile);
				int width = XaUtil.isEmpty(bimg)?0:bimg.getWidth();
				int height = XaUtil.isEmpty(bimg)?0:bimg.getHeight();
				Map<String, Integer> map = new HashMap<String, Integer>();
				map.put("pictureHeight", height);
				map.put("pictureWidth", width);
				xr.setCode(1);
				xr.setObject(XaConstant.Code.success + ":" + picturePath + "/"
						+ newName + ":" + height + ":" + width);
				return xr;
			} else {
				xr.setCode(0);
				xr.setObject(XaConstant.Code.error + ":上传文件类型不允许,请上传mp4/avi/rmvb/3gp/mov/wmv视频");
				return xr;
			}
		} catch (IllegalStateException e) {
			xr.setCode(0);
			xr.setObject(XaConstant.Code.error + ":图片上传失败(Il)");
			return xr;
		} catch (IOException e) {
			xr.setCode(0);
			xr.setObject(XaConstant.Code.error + ":图片上传失败(IO)");
			return xr;
		} catch (Exception e) {
			xr.setCode(0);
			xr.setObject(XaConstant.Code.error + ":图片上传失败(Ex)");
			return xr;
		}
	}
}

